package com.gl.servlet.filter;

import java.io.IOException;
import java.io.PrintStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.gl.servlet.listener.OnLineUserListener;

public class MaxClientFilter
  implements Filter
{
  private FilterConfig config = null;
  private String clientBeyondLimit = "clientBeyondLimit.jsp";

  public void init(FilterConfig config) throws ServletException {
    this.config = config;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    int maxClientCount = ((Integer)this.config.getServletContext().getAttribute("max-client-count")).intValue();
    int activeCount = OnLineUserListener.getActiveCount();
    if (activeCount > maxClientCount) {
      System.out.println("client Beyond Limit,max count[" + maxClientCount + "]");
      this.config.getServletContext().getRequestDispatcher("/" + this.clientBeyondLimit).forward(request, response);
    } else {
      chain.doFilter(request, response);
    }
  }

  public void destroy() {
    this.config = null;
  }
}